<template>
	<view class="store-container">
		<view class="image-section">
			<image :src="store.img || '/static/whb/youhui1.jpg'" mode="aspectFill" class="store-image"></image>
			<view class="image-counter">1/5</view>
		</view>

		<view class="details-section">
			<view class="store-name">{{ store.name }}</view>
			<view class="rating-sales">
				<uni-rate :size="16" :value="store.rete" :readonly="true" />
				<text>{{ store.rete }}分</text>
			</view>
			<view class="hours-address">
				<text>营业时间：{{ store.startTime }}--{{ store.endTime }}</text>
			</view>
			<view class="hours-address">
				<text>位置：{{ store.address }}</text>
				<image src="/static/whb/plane@3x.png" class="location-icon"></image>
			</view>
		</view>

		<view class="section-title">服务项目</view>
		<view class="service-items">
			<!-- 占位数据或单独获取 -->
			<view class="item" v-for="item in serviceItems" :key="item.name">
				<text class="item-name">{{ item.name }}</text>
				<view class="prices">
					<text class="current-price">¥ {{ item.currentPrice }}</text>
					<text class="original-price">¥ {{ item.originalPrice }}</text>
				</view>
			</view>
		</view>

		<view class="section-title">服务评价</view>
		<view class="service-reviews">
			<!-- 占位数据或单独获取 -->
			<view class="review-item" v-for="review in serviceReviews" :key="review.user">
				<image :src="review.avatar" mode="aspectFill" class="avatar"></image>
				<view class="review-content">
					<view class="user-date">
						<text class="user-name">{{ review.user }}</text>
						<text class="review-date">{{ review.time }}</text>
					</view>
					<uni-rate :size="14" :value="review.rate" :readonly="true" />
					<view class="review-text">{{ review.text }}</view>
					<view class="review-images" v-if="review.images && review.images.length">
						<image v-for="img in review.images" :key="img" :src="img" mode="aspectFill" class="review-image"></image>
					</view>
				</view>
				
			</view>
		</view>

		<view class="bottom-button-container">
			<button class="booking-btn" @click="goToBooking">立即预约</button>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad, onBackPress } from '@dcloudio/uni-app';

// 拦截返回操作
onBackPress(() => {
  // 跳转到指定页面
  uni.redirectTo({
    url: '/pages/index/nearstores/nearstores'
  });
  // 返回 true 表示拦截默认返回行为
  return true;
});

// 使用响应式变量存储店铺数据，初始为空对象
const store = ref({});
const serviceItems = ref([]);
const serviceReviews = ref([]);

// 获取用户信息
const fetchUserInfo = async (userId) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `http://localhost:9402/user/${userId}`,
			method: 'GET',
			header: {
				'Authorization': uni.getStorageSync('Token')
			},
			success: (res) => {
				// console.log('用户信息:', res);
				if (res.data.code === 200 && res.data.data) {
					resolve(res.data.data);
				} else {
					reject(new Error(res.data.msg || '获取用户信息失败'));
				}
			},
			fail: (error) => {
				reject(error);
			}
		});
	});
};

// 获取服务评价
const fetchServiceReviews = async (merchantId) => {
	uni.request({
		url: `http://localhost:9401/orders/evaluations/${merchantId}`,
		method: 'GET',
		header: {
			'Authorization': uni.getStorageSync('Token')
		},
		success: async (res) => {
			// console.log('服务评价:', res);
			if (res.data.code === 200 && res.data.data) {
				// 使用 Promise.all 并行获取所有用户信息
				const reviewsWithUserInfo = await Promise.all(
					res.data.data.map(async (review) => {
						try {
							const userInfo = await fetchUserInfo(review.userId);
							return {
								user: userInfo.userName ? userInfo.userName.substring(0, 1) + '**' : '匿名用户',
								avatar: userInfo.avatar || '/static/whb/youhui2.jpg',
								rate: review.rate,
								time: review.time,
								text: review.content,
								images: review.imgs ? review.imgs.split(',') : [],
								id: review.userId
							};
						} catch (error) {
							console.error('获取用户信息失败:', error);
							return {
								user: '匿名用户',
								avatar: '/static/whb/youhui2.jpg',
								rate: review.rate,
								time: review.time,
								text: review.content,
								images: review.imgs ? review.imgs.split(',') : [],
								id: review.userId
							};
						}
					})
				);
				serviceReviews.value = reviewsWithUserInfo;
			} else {
				uni.showToast({
					title: res.data.msg || '获取服务评价失败',
					icon: 'none'
				});
			}
		},
		fail: (error) => {
			console.error('获取服务评价失败:', error);
			uni.showToast({
				title: '网络请求失败，请重试',
				icon: 'none'
			});
		}
	});
};

// 获取服务列表
const fetchServices = (merchantId) => {
	uni.request({
		url: 'http://localhost:9401/fuwudetails/byMerchantAndType',
		method: 'GET',
		data: {
			merchantId: merchantId,
			typeId: 1,
			pageNum: 1,
			pageSize: 10
		},
		header: {
			'Authorization': uni.getStorageSync('Token')
		},
		success: (res) => {
			// console.log('服务列表:', res);
			if (res.data.code === 200 && res.data.rows) {
				serviceItems.value = res.data.rows.map(service => ({
					name: service.name,
					currentPrice: service.presentPrice,
					originalPrice: service.originalPrice,
					introduction: service.introduction || '暂无描述'
				}));
			} else {
				uni.showToast({
					title: res.data.msg || '获取服务列表失败',
					icon: 'none'
				});
			}
		},
		fail: (error) => {
			console.error('获取服务列表失败:', error);
			uni.showToast({
				title: '网络请求失败，请重试',
				icon: 'none'
			});
		}
	});
};

// 页面加载时根据 options 中的 id 获取商户详情
onLoad((options) => {
	if (options && options.id) {
		fetchMerchantDetails(options.id);
	}
});

// 获取商户详细信息函数
function fetchMerchantDetails(id) {
	uni.request({
		url: `http://localhost:9401/merchant/${id}`,
		method: 'GET',
		header: {
			'Authorization': uni.getStorageSync('Token')
		},
		success: (res) => {
			// console.log('商户详情:', res);
			if (res.data.code === 200 && res.data.data) {
				store.value = res.data.data;
				// 获取服务列表
				fetchServices(id);
				// 获取服务评价
				fetchServiceReviews(id);
			} else {
				uni.showToast({
					title: res.data.msg || '获取商户详细信息失败',
					icon: 'none'
				});
			}
		},
		fail: (error) => {
			console.error('获取商户详细信息网络请求失败:', error);
			uni.showToast({
				title: '网络请求失败，请重试',
				icon: 'none'
			});
		}
	});
}

// 跳转到预约页面
function goToBooking() {
	uni.navigateTo({
		url: '/pages/index/cheliangweixiu/cheliangweixiuyuyuw'
	});
}

</script>

<style>
.store-container {
	background-color: #f8f8f8;
	padding-bottom: 120rpx;
}

.back-icon, .more-icon {
	font-size: 24px; 
	color: #333;
	width: 44px;
	height: 44px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.back-icon {
    font-size: 20px; 
}

.image-section {
	position: relative;
	width: 100%;
	height: 400rpx; 
}

.store-image {
	width: 100%;
	height: 100%;
}

.image-counter {
	position: absolute;
	bottom: 20rpx;
	right: 20rpx;
	background-color: rgba(0, 0, 0, 0.5);
	color: #fff;
	padding: 4rpx 12rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
}

.details-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
	border-bottom: 1px solid #eee;
}

.store-name {
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.rating-sales {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.sales-text {
	font-size: 28rpx;
	color: #666;
	margin-left: 30rpx;
}

.hours-address {
	display: flex;
	align-items: center;
	font-size: 28rpx;
	color: #333;
	margin-bottom: 10rpx;
}

.location-icon {
	width: 36rpx;
	height: 36rpx;
	margin-left: 10rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	padding: 20rpx 30rpx;
	background-color: #fff;
	border-bottom: 1px solid #eee;
}

.service-items {
	background-color: #fff;
	margin-bottom: 20rpx;
	padding: 0 30rpx;
}

.item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1px solid #eee;
}

.item:last-child {
	border-bottom: none;
}

.item-name {
	font-size: 28rpx;
	color: #333;
}

.prices {
	display: flex;
	align-items: center;
}

.current-price {
	font-size: 32rpx;
	font-weight: bold;
	color: #ff4e4f;
	margin-right: 10rpx;
}

.original-price {
	font-size: 24rpx;
	color: #999;
	text-decoration: line-through;
}

.service-reviews {
	background-color: #fff;
	padding: 0 30rpx;
}

.review-item {
	display: flex;
	padding: 30rpx 0;
	border-bottom: 1px solid #eee;
}

.review-item:last-child {
	border-bottom: none;
}

.avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin-right: 20rpx;
}

.review-content {
	flex: 1;
}

.user-date {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10rpx;
}

.user-name {
	font-size: 28rpx;
	color: #333;
}

.review-date {
	font-size: 24rpx;
	color: #999;
}

.review-text {
	font-size: 28rpx;
	color: #333;
	margin: 10rpx 0;
	line-height: 1.5;
}

.review-images {
	display: flex;
	gap: 10rpx;
	margin-top: 10rpx;
}

.review-image {
	width: 150rpx;
	height: 150rpx;
	border-radius: 10rpx;
	object-fit: cover;
}

.bottom-button-container {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx 30rpx;
	background-color: #fff;
	box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
	z-index: 10;
}

.booking-btn {
	width: 100%;
	height: 88rpx;
	line-height: 88rpx;
	background-color: #007AFF; 
	color: #fff;
	font-size: 32rpx;
	border-radius: 44rpx;
	text-align: center;
}

</style>
